const {app, BrowserWindow,ipcMain} = require('electron')
const path = require("path")
const windowStateKeeper = require("electron-win-state").default
const cp = require('child_process')
const logger=require("./util/logger.js")
const {readHosts,writeHosts} = require("./util/util");
//执行cmd
async function  startDevServer(win) {


    const result=await cp.exec(`cd ${process.env.INIT_CWD} && npm run dev`, (err, stdout, stderr) => {
    })

    logger.info("dev server is runner on port "+3000)

    win.loadURL("http://localhost:3000")



}

const createLoginWindow=()=>{
    const winState = new windowStateKeeper({
        defaultWidth: 500,
        defaultHeight: 400
    })

    const win = new BrowserWindow({
        ...winState.winOptions,
        // backgroundColor: "#6435c9",
        webPreferences: {
            // 书写渲染进程中的配置
            // nodeIntegration: true, //开启true这一步很重要,目的是为了vue文件中可以引入node和electron相关的API
            // contextIsolation: false, // 可以使用require方法
            // enableRemoteModule: true, // 可以使用remote方法
            preload: path.resolve(__dirname, './preload/preload.js')
        }
    })


    // win.setMenu(null);  //隐藏顶部菜单

    win.center()

    // win.webContents.openDevTools()


    if (process.env.mode !== "dev") {
        win.loadFile(path.join(__dirname, "..", "dist/index.html")).then(r => {});
    } else {

        startDevServer(win).then(r => {})

    }
    // win.loadFile(path.resolve(__dirname, "./dist/index.html"))
    // win.loadURL("http://localhost:3001")
    win.on("ready-to-show", () => {

        win.setTitle(win.getTitle()+"*")
        const data = readHosts()

        win.webContents.send("set_content",data)
    })

    winState.manage(win)

    ipcMain.on("login_success",(event,args)=>{
        win.hide()
    })

    ipcMain.on("save_content",(event,data)=>{
        writeHosts(data)
    })


}
const createWindow = () => {

}


app.whenReady().then(() => {
    createLoginWindow()

})

app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createLoginWindow()
    }


})


app.on("window-all-closed", () => {
    app.exit(0)
})

